﻿using System;
using System.Windows.Forms;
using NHibernate;
using NHibernate.Cfg;
using Environment = NHibernate.Cfg.Environment;

namespace DCS.Infrastructure
{
    public class SessionProvider
    {
        private Configuration config;
        private readonly ISessionFactory sessionFactory;

        public SessionProvider(string connectionString)
        {

            ConnectToDataBase(connectionString);
            if (null == sessionFactory)
            {
                try
                {
                    sessionFactory = config.BuildSessionFactory();
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
            }
        }

        private void ConnectToDataBase(string connectionString)
        {
            config = new Configuration();
            config.Configure();

            if (connectionString != null)
            {
                config.Properties[Environment.ConnectionString] = connectionString;
            }
        }

        public ISession GetSession()
        {
            return sessionFactory.OpenSession();
        }
    }
}